package com.leyou.sh.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.sh.auth.dto.Payload;
import com.leyou.sh.auth.dto.UserDetail;
import com.leyou.sh.auth.utils.JwtUtils;
import com.leyou.sh.common.exception.LyException;
import com.leyou.sh.common.utils.RegexUtils;
import com.leyou.sh.user.dto.UserDTO;
import com.leyou.sh.user.entity.User;
import com.leyou.sh.user.mapper.UserMapper;
import com.leyou.sh.user.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.sh.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.sh.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;


/**
 * @author balisong_fcs
 * @date 2021/1/9 11:02
 * @desc
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //注入pc加密算法对象
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //定义一个将验证码存入redis中的关联key前缀,方便后期出去比对验证码是否正确
    private final String KEY_PREFIX = "ly:sms:phone:";


    @Override
    public Boolean exists(String data, Integer type) {
        if ((type != 1 && type != 2) || StringUtils.isEmpty(data) || (type == 2 && !RegexUtils.isPhone(data))) {
            throw new LyException(400, "傻逼,这都错了????");
        }
        return query()
                .eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count() == 1;
    }

    /**
     * 验证手机号规则合法性
     * 调用工具生成验证码,结合电话存入redis,
     * 调用mq将信息发送到消息队列
     *
     * @param phone
     */
    @Override
    public void sendCode(String phone) {
        //正则工具验证手机号格式是否合法
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "手机号有误");
        }
        //工具类随机生成6位数验证码
        String code = RandomStringUtils.randomNumeric(6);
        //保存验证码到redis
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
        //发送rabbitmq消息到ly-sms
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

    @Override
    @Transactional
    public void registerUser(User user, String code) {
        if (StringUtils.isEmpty(code)) {
            throw new LyException(400, "验证码不能为空");
        }
        String key = KEY_PREFIX + user.getPhone();
        //key不存在或者验证码不匹配
        if (!(redisTemplate.hasKey(key)) || !(code.equals(redisTemplate.opsForValue().get(key)))) {
            throw new LyException(400, "验证码不匹配");
        }
        //对密码进行加密，md5加盐加密，盐值在算法中，每一次的盐值都不相同
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));

        //保存用户
        this.save(user);
    }

    @Override
    public UserDTO queryUserByNameAndPassWord(String username, String password) {
        User user = this.query().eq("username", username).one();
        if (null == user) {
            throw new LyException(400, "搜索的用户不存在");
        }
        if (!bCryptPasswordEncoder.matches(password, user.getPassword())) {
            throw new LyException(400, "密码不匹配");
        }
        return new UserDTO(user);
    }

}
